<script setup>
import { getImageByIdApi, changeImageNameByIdApi, deleteImageByIdApi } from '@/api/image'
import { toast } from '@/utils/elnotification'
import { showprompt } from '@/utils/showprompt'
import { ref, computed } from 'vue'
import UploadFile from '@/components/upload-file.vue'

const props = defineProps({
  openChoose: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 1
  }
})

//分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const list = ref([])
const loading = ref(false)
const imageId = ref(0)

const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getImageByIdApi(imageId.value, currentPage.value)
    list.value = res.list.map((item) => {
      item.checked = false
      return item
    })
    total.value = res.totalCount
  } finally {
    loading.value = false
  }
}
//根据分类id重新加载图片列表
const loadData = (id) => {
  currentPage.value = 1
  imageId.value = id
  getData()
}

//重命名
const onChangeName = async (item) => {
  const { value, action } = await showprompt('重命名', item.name)
  if (action !== 'confirm') return
  loading.value = true
  try {
    await changeImageNameByIdApi(item.id, value)
    toast('修改成功')
    getData()
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除图片
const onDeleta = async (id) => {
  loading.value = true
  try {
    await deleteImageByIdApi([id])
    toast('删除成功')
    getData()
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//显示抽屉组件
const drawer = ref(false)
const showDrawer = () => (drawer.value = true)

//上传图片成功
const onSuccess = () => {
  getData(1)
}

//选中图片
const emit = defineEmits(['choose'])
const chooseImage = computed(() => list.value.filter((item) => item.checked))
const onChangeChecked = (item) => {
  if (item.checked && chooseImage.value.length > props.limit) {
    item.checked = false
    return toast(`最多只能选中${props.limit}张`, 'error')
  }
  emit('choose', chooseImage.value)
}

//暴露方法
defineExpose({
  loadData,
  showDrawer
})
</script>

<template>
  <el-main class="image-main" v-loading="loading">
    <div class="top p-3">
      <el-row :gutter="10">
        <el-col :span="6" v-for="(item, index) in list" :key="index" :offset="0">
          <el-card
            shadow="hover"
            class="relative mb-3"
            :body-style="{ padding: 0 }"
            :class="{ 'border-blue-500': item.checked }"
          >
            <el-image
              :preview-src-list="[item.url]"
              :initial-index="0"
              :src="item.url"
              fit="cover"
              :lazy="true"
              class="h-[150px]"
              style="width: 100%"
            >
            </el-image>
            <div class="image-title">{{ item.name }}</div>
            <div class="flex justify-center items-center p-2">
              <el-checkbox
                v-if="openChoose"
                v-model="item.checked"
                @change="onChangeChecked(item)"
              />

              <el-button type="primary" size="small" text @click="onChangeName(item)"
                >重命名</el-button
              >
              <el-popconfirm
                title="是否要删除该图片"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="onDeleta(item.id)"
              >
                <template #reference>
                  <el-button type="primary" size="small" class="!mx-0" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="bottom">
      <el-pagination
        :current-page="currentPage"
        :page-size="limit"
        background
        layout="prev,pager, next"
        :total="total"
        @current-change="getData"
      />
    </div>
  </el-main>
  <el-drawer v-model="drawer" title="上传图片">
    <UploadFile :data="{ image_class_id: imageId }" @success="onSuccess"></UploadFile>
  </el-drawer>
</template>

<style>
.image-main {
  position: relative;
}

.image-main .top {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 50px;
  overflow-y: auto;
}
.image-main .bottom {
  position: absolute;
  bottom: 0;
  height: 50px;
  left: 0;
  right: 0;
  @apply flex items-center justify-center;
}
.image-title {
  position: absolute;
  top: 122px;
  left: -1px;
  right: -1px;
  @apply text-sm truncate text-gray-100 bg-opacity-50 bg-gray-800 px-2 py-1;
}
</style>
